package net.freebytes.ssmp.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import net.freebytes.ssmp.entity.Role;
import net.freebytes.ssmp.mapper.RoleMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author 千里明月
 * @date 2021/7/20
 **/
@Service
public class RoleService extends ServiceImpl<RoleMapper, Role> {


    private static LoadingCache<String, List<Role>> roleCache;

    public RoleService() {
        //启用缓存，容量为1000，过期时间为30分钟
        roleCache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(30, TimeUnit.MINUTES).
                build(new CacheLoader<String, List<Role>>() {
                    @Override
                    public List<Role> load(String uid) {
                        //如没有该缓存键值，那么就写入缓存
                        return getBaseMapper().getRoleByUserId(uid);
                    }
                });
    }

    public boolean insertRole(Role role) {
        Role one = super.getOne(new QueryWrapper<Role>().lambda().eq(Role::getName, role.getName()));
        if (one != null) {
            throw new RuntimeException(("角色已存在"));
        }
        return super.save(role);
    }

    /**
     * 从缓存中获取 用户角色
     *
     * @param uid
     * @return 角色列表
     * @author 千里明月
     * @date 2021/7/23
     **/
    public List<Role> cacheRoleByUserId(String uid) {
        List<Role> roles = null;
        try {
            roles = roleCache.get(uid);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return roles;
    }

    public void deleteCache(String uid) {
        roleCache.asMap().remove(uid);
    }

    public Role get(String id) {
        return super.getById(id);
    }

    public boolean delete(String id) {
        return super.removeById(id);
    }

//    public Role getRoleWithPerm(String roleId) {
//        List<String> permIds = rolePermService.getPermIdByRole(roleId);
//        Collection<Permissions> permissions = permService.listByIds(permIds);
//
//        Set<Permissions> set = permissions.stream().collect(Collectors.toSet());
//        Role role = get(roleId);
//        role.setPermissions(set);
//        return role;
//    }
}
